const {readJson,writeJson} = require('../../until/fs');
const {ADMINUSER_JSON,ADMIN_UID} = require('../../config/config.data');
const getCookies = require('../../until/getCookies');
const uuid = require('node-uuid')

// 登录接口
let adminLoginIn = (req,res)=>{

    // 获取账号密码
    const {user,pwd} = req.body;
    // 读取我们的用户信息表
    let userData = readJson(ADMINUSER_JSON);

    // 判断账号是否存在
    let searchRes = userData.find(item=>item.user === user)

    if(!searchRes){
        res.send({code:0,msg:'账号不存在',data:[]})
        return
    }
    
    if(searchRes.pwd !== pwd){
        res.send({code:0,msg:'密码错误',data:[]})
        return
    }
    
    if(searchRes.status !== 'ok'){
        res.send({code:0,msg:'您已被管理员限制登录'})
        return
    }

    //基于时间戳 生成随机字符串 v4随机字符串
    let adminuid = uuid.v1()

    // 在服务端缓存一个用户状态
    ADMIN_UID.push({adminuid})

    // 往前端的cookie写入一个唯一标识记录用户状态
    res.cookie('adminuid',adminuid)

    // 记录后台账号最近登录时间
    let index = userData.findIndex(item=>item.user === user);
    userData[index].nearTime = new Date().getTime();

    res.send({code:1,msg:'登陆成功',data:searchRes.user})

}

let adminLoginOut = (req,res)=>{
      // 获取客户端uid
      let adminuid = getCookies(req.get('cookie'),'adminuid');

      // 通过uid从缓存中筛查缓存用户状态
      let index = ADMIN_UID.findIndex(item=>item.adminuid === adminuid);
  
      // 对缓存用户状态进行清除
      if(index>-1){
            ADMIN_UID.splice(index,1)
      }
  
      // 清除客户端的cookie中的uid
      res.clearCookie('adminuid')
      
      res.send({code:1,msg:'退出成功',data:[]})
}


// 管理员列表

let getAdminList = (req,res)=>{
    let adminData = readJson(ADMINUSER_JSON);
    res.send({code:1,msg:'请求成功',data:adminData})
    
}


// 管理员账号添加

let addAdminList =(req,res)=>{
    const {user,pwd} = req.body;
    let adminData = readJson(ADMINUSER_JSON);
    // 判断账号是否存在
    let searchRes = adminData.find(item=>item.user === user)

    if(searchRes){
        res.send({code:0,msg:'账号已存在'})
        return
    }

    adminData.push({
        userid:uuid.v1(),
        user,
        pwd,
        status:'ok',
        createTime:new Date().getTime(),
        nearTime:0
    })
    writeJson(ADMINUSER_JSON,adminData)
    res.send({code:1,msg:'添加成功'})

}

let editAdminList = (req,res)=>{
    const {user} = req.body;
    let adminData = readJson(ADMINUSER_JSON);
    let index = adminData.findIndex(item=>item.user === user)
    if(index===-1){
        res.send({code:0,msg:'操作失败'})
        return
    }
    adminData[index].status = 'cancel';
    writeJson(ADMINUSER_JSON,adminData)

    res.send({code:1,msg:'操作成功'})
}
module.exports = {
    adminLoginIn,adminLoginOut,getAdminList,addAdminList,editAdminList
}